<template>
  <el-card>
    <template #header>权限管理</template>

    <template>
      <!-- 1.0 查询表单 -->

      <!-- 2.0 数据表格 -->
      <el-row class="setting-btn">
        <el-col > <el-button size="mini" type="primary" @click="dialogVisible = true">添加权限</el-button>  </el-col>
        <el-col > <el-button size="mini" type="danger" @click="delAll">批量删除</el-button> </el-col>
        <el-col > <el-button size="mini" type="default" @click="toggleSelection()">取消选择</el-button> </el-col>
      </el-row>

      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        border
        row-key="powerId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="powerName" label="权限名称" width="140"> </el-table-column>
        <el-table-column label="图标">
          <template v-slot="{ row }">
            <i :class="row.icon"></i>
          </template>
        </el-table-column>
        <el-table-column prop="powerType" label="权限类型"> </el-table-column>
        <el-table-column label="是否启用">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.enable"
              :active-value="1"
              :inactive-value="0"
              @change="changeSate(row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序"> </el-table-column>
        <el-table-column label="操作" width="210">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="editPower(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="delPower(row.powerId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加权限 -->
      <el-dialog title="添加新权限" :visible.sync="dialogVisible" width="45%" @close="resetForm('addPower')">
        <el-form ref="addPower" :model="powerForm" label-width="80px">
          <el-form-item label="父级" prop="parentId">
              <el-cascader
                v-model="powerForm.parentId"
                :options="tableData"
                :props="{ checkStrictly: true }"
                @change="handleChange"
                clearable></el-cascader>
          </el-form-item>
          <el-form-item label="权限名称" prop="powerName">
            <el-input v-model="powerForm.powerName"></el-input>
          </el-form-item>
          <el-form-item label="标识" prop="powerCode">
            <el-input v-model="powerForm.powerCode"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="powerType">
              <el-radio-group v-model="powerForm.powerType">
                <el-radio label="0">目录</el-radio>
                <el-radio label="1">菜单</el-radio>
                <el-radio label="2">按钮</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="路径" prop="powerUrl">
            <el-input v-model="powerForm.powerUrl"></el-input>
          </el-form-item>
          <el-form-item label="打开" prop="openType">
             <el-select v-model="powerForm.openType" placeholder="请选择打开方式">
                <el-option label="框架" value="_blank"></el-option>
                <el-option label="签页" value="_blank"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="图标" prop="icon">
             <el-select v-model="powerForm.icon" placeholder="请选择图标">
                <!-- <el-option label="框架" value="_blank"></el-option> -->
                <!-- <el-option label="签页" value="_blank"></el-option> -->
              </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="powerForm.sort"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('addPower')">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm('addPower')">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑权限 -->
      <el-dialog title="编辑权限" :visible.sync="editDialogVisible" width="45%" @close="resetForm('editPower')">
        <el-form ref="editPower" :model="editPowerForm" label-width="80px">
          <el-form-item label="父级" prop="parentId">
              <el-cascader
                v-model="editPowerForm.parentId"
                :options="tableData"
                :props="{ checkStrictly: true }"
                @change="handleChange"
                clearable></el-cascader>
          </el-form-item>
          <el-form-item label="权限名称" prop="powerName">
            <el-input v-model="editPowerForm.powerName"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="powerType">
              <el-radio-group v-model="powerForm.powerType">
                <el-radio label="0">目录</el-radio>
                <el-radio label="1">菜单</el-radio>
                <el-radio label="2">按钮</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="图标" prop="icon">
             <el-select v-model="editPowerForm.icon" placeholder="请选择图标">
                <!-- <el-option label="框架" value="_blank"></el-option> -->
              </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="editPowerForm.sort"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('editPower')">取 消</el-button>
          <el-button size="mini" type="primary" @click="confirmEdit('editPower')">确 定</el-button>
        </span>
      </el-dialog>

    </template>
  </el-card>
</template>

<script>
  import { getPerList, addPower, delPower, batchPower, enablePower, disablePower } from '@/api/powers'
  import _ from 'lodash'

  export default {
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableData: [],
        multipleSelection: [],
        powerForm: {
          icon: "",
          openType: "",
          parentId: [],
          powerCode: "",
          powerName: "",
          powerType: "1",
          powerUrl: "",
          selectParent_select_input: "",
          sort: ""
        },
        dialogVisible: false,
        editDialogVisible: false,
        options: [],
        // 所有的数据
        allData: [],
        editPowerForm: {
          icon: "",
          parentId: [],
          powerName: "",
          powerType: "1",
          selectParent_select_input: "",
          sort: ""
        }
      }
    },
    created() {
      this.initData()
    },
    methods: {
      async initData() {
        const { data } = await getPerList()
        // 递归算法完成数据嵌套
        function getData(arr, i) {
          let newArr = []
          if(Array.isArray(arr)) {
            newArr =  data.filter(item => item.parentId === i)
            newArr.forEach(item => {
              const list = getData(newArr, item.powerId)
              if(list.length > 0) {
                item.children = list
              }
            })
          }
          return newArr
        }
        // 获取下拉框数据
        function getSelect(arr) {
          arr.forEach(item => {
            item.label = item.powerName
            item.value = item.powerId
            item.children && getSelect(item.children)
          })
        }
        this.allData = _.cloneDeep(data)
        this.tableData = getData(data, '0')
        getSelect(this.tableData)
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          });
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 重置表单
      resetForm(formName) {
        this.dialogVisible = false
        this.editDialogVisible = false
        this.$refs[formName].resetFields()
      },
      // 添加用户
      submitForm(formName) {
            console.log(this.powerForm.parentId)
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const arr = this.powerForm.parentId || []
            this.powerForm.parentId = arr[arr.length - 1] || '0'
            const { success, msg} = await addPower(this.powerForm)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
              this.$refs[formName].resetFields()
            }
          } else {
            return false
          }
        });
      },
      // 删除用户
      delPower(id) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {success, msg} = await delPower(id)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      // 批量删除
      delAll() {
        if(this.multipleSelection.length <= 0) return
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const ids = this.multipleSelection.map(item => item.powerId)
          const {success, msg} = await batchPower({ ids })
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      handleChange(value) {
        const id = value[value.length - 1]
        this.powerForm.selectParent_select_input = this.allData.find(item => item.powerId === id).powerName
      },
      // 改变状态
      async changeSate(row) {
        if(row.enable) {
          const {success, msg} = await enablePower({ powerId: row.powerId })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }else {
          const {success, msg} = await disablePower({ powerId: row.powerId })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }
      },
      // 回写编辑数据
      editPower(row) {
        const arr = [row.powerId]
        const _that = this
        // 通过list递归到可以回写的权限
        function getIds(o) {
          if(o.parentId !== '0') {
            const item = _that.allData.find(item => item.powerId === o.parentId)
            arr.unshift(item.powerId)
            getIds(item)
          }
        }
        getIds(row)
        this.editPowerForm = {
          icon: row.icon,
          parentId: arr,
          powerName: row.powerName,
          powerType: row.powerId,
          selectParent_select_input: row.selectParent_select_input,
          sort: row.sort
        }
        this.editDialogVisible = true
      },
      // 确认编辑
      confirmEdit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const arr = this.powerForm.parentId || []
            this.powerForm.parentId = arr[arr.length - 1] || '0'
            const { success, msg} = await addPower(this.powerForm)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
              this.$refs[formName].resetFields()
            }
          } else {
            return false
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
.setting-btn {
  display: flex;
  .el-col {
    width: 100px;
  }
}

.el-table {
  margin: 24px 0;
}

.el-dialog {
  .el-select, .el-cascader {
    width: 100%;
  }
}
</style>